package com.ny.zmb.openapi.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.ny.zmb.glxt.entity.PmStore;
import com.ny.zmb.glxt.service.IPmStoreService;
import com.ny.zmb.openapi.constant.PHPConstant;
import com.ny.zmb.openapi.controller.entity.Result;
import com.ny.zmb.openapi.entity.PmUser;
import com.ny.zmb.openapi.entity.PmUserToken;
import com.ny.zmb.openapi.entity.PmUserVLog;
import com.ny.zmb.openapi.service.IPmUserService;
import com.ny.zmb.openapi.service.IPmUserTokenService;
import com.ny.zmb.openapi.service.IPmUserVLogService;
import com.ny.zmb.openapi.ysutil.base.EYinShengBase;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

/**
 * 用户个人中心
 */
@CrossOrigin
@RestController
@RequestMapping("user")
public class UserController extends EYinShengBase {

    @Resource
    private IPmUserTokenService pmUserTokenService;
    @Resource
    private IPmUserService pmUserService;
    @Resource
    private IPmStoreService storeService;
    @Resource
    private IPmUserVLogService pmUserVLogService;

    /**
     * 用户个人中心
     *
     * @return
     */
    @GetMapping("userDetail")
    public Result userIndex(@RequestHeader(name = "token") String token) {
        Map<String, Object> dataMap = new HashMap<>();
        PmUserToken userDetailByToken = this.pmUserTokenService.getUserDetailByToken(token);
        PmUser byId = this.pmUserService.getById(userDetailByToken.getUserId());
        PmStore store = this.storeService.getInfoByUserId(userDetailByToken.getUserId());
        dataMap.put("user", byId);
        dataMap.put("store", store);
        return Result.ok(dataMap);
    }

    @GetMapping("/getUserInfo")
    public Result getUserInfo() {
        PmUserToken pmUserToken = getUserToken();
        Integer userId = pmUserToken.getUserId();
        PmUser pmUser = pmUserService.getById(userId);
        return pmUser != null ? Result.ok("成功", pmUser) : Result.fail("未找到用户信息");
    }

    /**
     * 个人v值
     *
     * @return
     */
    @GetMapping("userVLog")
    public Result userVLog(@RequestParam(name = "pageNo", defaultValue = "1", required = false) Integer pageNo,
                           @RequestParam(name = "pageSize", defaultValue = "10", required = false) Integer pageSize, Integer userId) {
        Page<PmUserVLog> page = new Page<>(pageNo, pageSize);
        LambdaQueryWrapper<PmUserVLog> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(PmUserVLog::getUserId, userId);
        wrapper.orderByDesc(PmUserVLog::getCreatetime);
        return Result.ok(this.pmUserVLogService.page(page, wrapper));
    }

    @GetMapping("getMyInvitation")
    public Result getMyInvitation() throws Exception{
        PmUserToken pmUserToken = getUserToken();
        Integer userId = pmUserToken.getUserId();
        PmUser pmUser = pmUserService.getById(userId);
        String inviteCode = pmUser.getInviteCode();
        String inviteCodeUrl = PHPConstant.BASE_URL + "/mobile?invitationCode=" + inviteCode;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("inviteCode", inviteCode);
        jsonObject.put("inviteCodeUrl", inviteCodeUrl);
        BufferedImage qrCodeImage = createQrCodeImage(inviteCodeUrl, 300, 300);
        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        ImageIO.write(qrCodeImage,"png",bs);
        byte[] bytes = bs.toByteArray();
        String s = Base64.getEncoder().encodeToString(bytes);
        jsonObject.put("base64",s);
        return Result.ok("成功", jsonObject);
    }

    /**
     *  生成二维码图片并返回
     * @param content 二维码存储的内容
     * @param width   指定二维码的宽度
     * @param height  指定二维码的高度
     * @return
     * @throws Exception
     */
    public static BufferedImage createQrCodeImage(String content, int width, int height) throws Exception{
        Hashtable hints = new Hashtable();
        //指定纠错等级
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        //生成二维码矩阵
        BitMatrix bitMatrix =
                new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
        //获取矩阵宽度、高度,生成二维码图片
        BufferedImage image = new BufferedImage(bitMatrix.getWidth(),bitMatrix.getHeight(),BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        return image;
    }
}
